<?php
/**
 * Class Db
 *
 * @author mr.trieu
 */
class DB{

	protected $host = SERVER;
	protected $userName = USER;
	protected $password = PASS;
	protected $dbName = DBNAME;
	protected $connect;
	protected $result;
	protected $die = "Error: Could not connect to database";
	protected $notdata = "Error: Could not find database ";

	public function __construct() {
		return $this->connection();
	}

	function __destruct() {
	}

	public function saveLog($msg = '') {
		global $log;
// 		$log->writeLog($msg);
	}

	/*
	 * Connect to database author: mr.trieu
	 */
	private function connection() {

		$this->connect = mysql_pconnect($this->host, $this->userName, $this->password) or die($this->die);
		if (!$this->connect)
			$this->log->writeLog($this->die);

		if (!is_null($this->dbName))
			mysql_select_db($this->dbName, $this->connect) or die($this->notdata . $this->dbName);
		else
			$this->saveLog($this->notdata . $this->dbName);
	}

	function disconnect() {
		if ($this->connect)
			mysql_close($this->connect);
	}

	function charset() {
		if ($this->connect){
			mysql_query('SET NAMES "utf8"', $this->connect);
			mysql_query('SET CHARACTER SET utf8', $this->connect);
			mysql_query('SET CHARACTER_SET_CONNECTION=utf8', $this->connect);
			mysql_query('SET SQL_MODE = ""', $this->connect);
		}
	}

	function list_tables($dbname) {
		return @mysql_list_tables($dbname, $this->connect);
	}

	/*
	 * Query
	 * @author	mr.Trieu
	 */
	function Query($query) {

		global $nQueries;

		$this->charset();

		$result = mysql_query($query, $this->connect);

		if (!$result){
			$Error = 'Error: ' . mysql_error($this->connect) . '<br />Error No: ' . mysql_errno($this->connect) . '<br />' . $query;
			$this->saveLog($Error);
			trigger_error($Error);
			exit();
		}

		// Count number of SQL queries
		$nQueries = !isset($nQueries) ? 1 : $nQueries + 1;

		return $result;
	}

	/*
	 * fetch row @param string $query @return multitype: @author mr.Trieu
	 */
	function fetchRow($query) {

		$result = $this->Query($query);

		if (!$result){
			$Error = 'Could not run query: ' . mysql_error();
			$this->saveLog($Error);
			trigger_error($Error);
			exit();
		}else{
			return mysql_fetch_row($result);

			/* Now we free up the result and continue on with our script */
			mysql_free_result($result);
		}
	}

	/*
	 * fetch one @param string $query @return mixed @author mr.Trieu
	 */
	function fetchOne($query) {
		$result = $this->Query($query, $this->connect);

		if (!$result){
			$Error = 'Could not run query: ' . mysql_error();
			$this->saveLog($Error);
			trigger_error($Error);
			exit();
		}else{
			$row = mysql_fetch_row($result);

			return current($row);

			/* Now we free up the result and continue on with our script */
			mysql_free_result($result);
		}
	}

	/*
	 * Fetch all array param string $query return multitype: while loop author: mr.Trieu
	 */
	function fetchAll($query) {
		$results = array();
		$result = $this->Query($query, $this->connect);

		if (!$result){
			$Error = 'Could not run query: ' . mysql_error();
			$this->saveLog($Error);
			trigger_error($Error);
			exit();
		}else{
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
				$results[] = $row;
			}

			return $results;
			unset($results);

			/* Now we free up the result and continue on with our script */
			mysql_free_result($result);
		}
	}

	/*
	 * num rows @param string $query @author mr.Trieu
	 */

	function numRows($query) {

		$result = $this->Query($query, $this->connect);

		if (!$result){
			$Error = 'Could not run query: ' . mysql_error();
			$this->saveLog($Error);
			trigger_error($Error);
			exit();
		}else{
			return mysql_num_rows($result);

			/* Now we free up the result and continue on with our script */
			mysql_free_result($result);
		}
	}

	/*
	 * get affected rows return number author mr.Trieu
	 */
	function getAffectedRows() {
		return mysql_affected_rows($this->connect);
	}

	/*
	 * insert @param string $tableName @param string $data @return number @author mr.Trieu
	 */

	function insert($tableName, $data, $quote = false) {

		if (!is_array($data) || is_null($tableName))
			die('Insert error');

		$query = "INSERT INTO {$tableName}";

		/**
		 * create array $field => $value
		 * example:
		 * $info = array("user" => $username, "email" => $email, "pass" =>
		 * $pwd);
		 * $table = "users";
		 * insert new user and get their new id
		 * $id = insert($table, $info);
		 */

		$fields = array_keys($data);
		$keyField = '';
		$valueField = '';

		if (count($fields)){
			foreach ($fields as $field){
				$keyField .= $field . ',';

				if ($quote)
					$valueField .= '"' . $data[$field] . '",';
				else
					$valueField .= "'" . $data[$field] . "',";
			}

			$keyField = '(' . substr($keyField, 0, -1) . ')';
			$valueField = '(' . substr($valueField, 0, -1) . ')';
		}

		$query .= $keyField . ' VALUES ' . $valueField;

//		echo $query;

		$this->Query($query);
		return mysql_insert_id($this->connect);
	}

	/*
	 * Insert multiple records into MySQL with a single query INSERT INTO example (example_id, name, value, other_value) VALUES (100, 'Name 1', 'Value 1', 'Other 1'), 103, 'Name 4', 'Value 4', 'Other 4');
	 */
	function insertMultiLang($tableName, $id, $fields, $values) {
		if (!is_array($fields) || !is_array($values) || is_null($tableName))
			die('Insert error');

		global $db;

		$query = "INSERT INTO {$tableName}";

		$keyField = '';
		$valueField = '';

		if (count($fields)){
			foreach ($fields as $field){
				$keyField .= $field . ',';
			}
			$keyField = '(' . substr($keyField, 0, -1) . ')';
		}

		if (count($values)){
			foreach ($values as $key=>$value){
				$valueField .= "(" . $id . ", '" . $db->clean($key) . "', '" . $db->clean($value) . "'),";
			}
			$valueField = substr($valueField, 0, -1);
		}

		$query .= $keyField . ' VALUES ' . $valueField;
//		echo $query;


		self::Query($query);
	}

	/*
	 * update @param string $tableName @param string $data @param string $where @return number @author mr.Trieu
	 */

	function update($tableName, $data, $where, $quote = false) {

		if (!is_array($data) || is_null($tableName))
			die('Update error');

		if (!$where)
			die('Where clause is null');

		$query = "UPDATE {$tableName} SET ";

		/**
		 * create array $field => $value
		 * example:
		 * $table = 'users';
		 * $info = array("user" => $username, "email" => $email, "pass" => $pwd);
		 * $where = 'id = 10';
		 * update($table, $info, $where);
		 */
		$fields = array_keys($data);

		if (count($fields)){
			foreach ($fields as $field){
				if ($quote)
					$query .= $field . '="' . $this->clean($data[$field], true) . '",';
				else
					$query .= $field . "='" . $data[$field] . "',";
			}

			$query = substr($query, 0, -1);
		}

		if (!is_null($where))
			$query .= ' WHERE ' . $where;

// 		echo '<pre>' . $query . '</pre>';

		$this->Query($query);
		mysql_affected_rows($this->connect);

		return true;
	}

	/*
	 * delete @param string $table @param string $where @return number @author mr.Trieu
	 */

	function delete($table, $where) {

		if (!$table)
			die('Table not found');

		if (!$where)
			die('Where clause is null');

		$query = "DELETE FROM {$table} WHERE " . $where;

		// echo '<pre>' . $query . '</pre>';


		$this->Query($query);
		return mysql_affected_rows($this->connect);
	}

	function clean($str, $encode_ent = false) {
		$str = trim($str);

		if ($encode_ent)
			$str = htmlentities($str);

		if (version_compare(phpversion(), '4.3.0') >= 0){
			if (get_magic_quotes_gpc())
				$str = stripslashes($str);

			if (mysql_ping())
				$str = mysql_real_escape_string($str);
			else
				$str = addslashes($str);
		}else{
			if (!get_magic_quotes_gpc())
				$str = addslashes($str);
		}

		return $str;
	}
}